/*
@hehung
email: 1398660197@qq.com
wechat: hehung95
reproduced and please indicate the source @hehung
*/

#include "app_common.h"

#define WARNING_DEBUG
#undef WARNING_DEBUG

#ifdef WARNING_DEBUG
#include <stdio.h>
#define LOG(fmt, ...)        printf(fmt, ##__VA_ARGS__)
#endif


#define MQ5_THD_TOLERANCE          (100U)

static uint32_t mq5_warning_thrd = 3800;  // ppm
static uint8_t  mq5_warning_flag = 0U;
static uint8_t  mq5_warning_switch = 0U;
static bool  mq5_thrd_update_flg = false;


void Warning_Init(void)
{
	// Read threshold from EEPROM
	
}

void Warning_Running(void)
{
	uint32_t mq5_value = Mq5_GetGasPpmValue();
	
	// MQ5 warning
	if (mq5_value >= mq5_warning_thrd)
	{
		// warning alarm
		mq5_warning_flag = 1U;
	}
	else if (mq5_value <= mq5_warning_thrd - MQ5_THD_TOLERANCE)
	{
		mq5_warning_flag = 0U;
	}
	
	if (1U == mq5_warning_flag)
	{
		//
		if (1U == mq5_warning_switch)
		{
			// Beep
			if (false == Beep_GetStatus())
			{
				Beep_On();
			}
		}
		else
		{
			if (true == Beep_GetStatus())
			{
				// off beep
				Beep_Off();
			}
		}
	}
	else 
	{
		if (true == Beep_GetStatus())
		{
			// off beep
			Beep_Off();
		}
	}
	
	// Update the EEPROM data
	if (true == mq5_thrd_update_flg)
	{
		mq5_thrd_update_flg = false;
		Eeprom_UpdateKeyData();
	}
}

uint32_t Warning_GetMq5Threshold(void)
{
	return mq5_warning_thrd;
}

void Warning_SetMq5Threshold(uint32_t mq5_thrd)
{
	mq5_warning_thrd = mq5_thrd;
	mq5_thrd_update_flg = true;
}

uint8_t Warning_GetMq5WarningSwitch(void)
{
	return mq5_warning_switch;
}

void Warning_SetMq5WarningSwitch(uint8_t w_sw)
{
	mq5_warning_switch = w_sw;
}
